<?php
namespace app\admin\controller;

use app\BaseController;
use app\common\model\mysql\CommonAdmin as models;
use app\common\validate\CommonAdmin as validateModel;
use think\exception\ValidateException;
use app\common\business\mysql\CommonAdmin as serviceModel;

class CommonAdmin extends BaseController
{

    /*
     * 所有数组
     */
    public function list(){
        $fildes = 'page,word';
        $receiveData = getData($this->request->post(),$fildes);
        if(empty($receiveData['page'])){
            $receiveData['page'] = 1;
        }
        $where = [];
        if(!empty($receiveData['word'])){
            $where[] = ['username|mobile','like','%'.$receiveData['word'].'%'];
        }
        $limit_start = ($receiveData['page']-1) * env('page_size');
        $data = [
            'lists' => serviceModel::getList($where,$limit_start,env('page_size')),
            'allpage' => serviceModel::getCount($where)
        ];
        //返回参数
        jsonSuccess($data);
    }

    /*
     * 修改和编辑
     */
    public function edit(){
        $fildes = "id,username,password,role_id,remark,mobile,status,city_config_arr,token";
        $receiveData = getData($this->request->post(),$fildes);
        //校验token
        $admin = serviceModel::checkToken($receiveData['token']);
        try {
            if(!empty($receiveData['id'])){
                validate(validateModel::class)->scene('edit')->check($receiveData);
            }else{
                validate(validateModel::class)->scene('add')->check($receiveData);
            }
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            jsonFail($e->getError());
        }
        $load = serviceModel::getOne(['username'=>$receiveData['username']]);
        if(!empty($receiveData['id'])){
            if(!empty($load) && $load['id'] != $receiveData['id']){
                jsonFail('已存在相同用户名');
            }
            if(!empty($receiveData['password'])){
                if(strlen($receiveData['password']) < 6){
                    jsonFail('密码不能少于6位');
                }
            }
            serviceModel::edit($receiveData,$admin);
        }else{
            if(!empty($load)){
                jsonFail('已存在相同用户名');
            }
            serviceModel::insert($receiveData,$admin);
        }
        jsonSuccess();
    }

    public function delete(){
        $fildes = "id,token";
        $receiveData = getData($this->request->post(),$fildes);
        //校验token
        $admin = serviceModel::checkToken($receiveData['token']);
        $load = serviceModel::getOne(['id'=>$receiveData['id']]);
        if(empty($load)){
            jsonFail('删除的管理员不存在');
        }
        if($load['is_no_delete'] == 1){
            jsonFail('该管理员不可删除');
        }
        serviceModel::delete($receiveData,$admin,$load);
        jsonSuccess();
    }

}
